package com.sendpo.zjx.sendpo.fragment.storeallproduce;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.github.czy1121.view.CornerLabelView;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.GeneicStoreInfoActivity;
import com.sendpo.zjx.sendpo.domain.MerchandiseStoreDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/8/19.
 */

public class AllProduceFragment extends StoreAllProduceBaseFragment {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    Unbinder unbinder;
    private LinearLayoutManager lm;

    private RecylcerAdaper adpter;
    private int currentlastitem=0;
    private boolean lastloading=false;
    public int pagenow=1;
    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_allproduce, null);
        ButterKnife.bind(view, mActivity);
        return view;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initData();
        return rootView;
    }
   public void initData(){

       lm=new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL,false);
       recyclerview.setLayoutManager(lm);
       pagenow=1;
        query(pagenow);
   }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerchandiseStoreDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<MerchandiseStoreDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_generic_store_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final MerchandiseStoreDomain.DataBean  dataBean=dataBeen.get(position);
            ih.shopping_title_user.setText(""+dataBean.getMerchandiseName());
            ih.shopping_info_user.setText(""+dataBean.getMerchandiseDetails());
            Glide.with(AllProduceFragment.this)
                    .load(""+dataBean.getMerchandiseHeadimg())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .override(500,500)
                    .into(ih.icon);
            ih.now_tv.setText("¥"+dataBean.getMerchandiseCurrentprice());
            ih.origin_tv.setText("¥"+dataBean.getMerchandiseOriginalprice());

            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("merchandiseId",dataBean.getMerchandiseId());
                    Tools.redirectActivity(mActivity, GeneicStoreInfoActivity.class,map);
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public ImageView icon;
            public TextView origin_tv;
            public TextView shopping_title_user;
            public TextView shopping_info_user;
            public TextView now_tv;
            public TextView song_tv;
            public TextView xiandao_tv;
            public CornerLabelView labelview;
            public IndexHoler(View itemView) {
                super(itemView);
                labelview=itemView.findViewById(R.id.labelview);
                song_tv=itemView.findViewById(R.id.song_tv);
                now_tv=itemView.findViewById(R.id.now_tv);
                xiandao_tv=itemView.findViewById(R.id.xiandao_tv);
                rootView = itemView;
                icon = itemView.findViewById(R.id.icon);
                origin_tv= itemView.findViewById(R.id.origin_tv);
                origin_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
                origin_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线
                origin_tv.getPaint().setAntiAlias(true);// 抗锯齿
                origin_tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰
                shopping_title_user=itemView.findViewById(R.id.shopping_title_user);
                shopping_info_user=itemView.findViewById(R.id.shopping_info_user);
            }
        }

        public void deleteRow(int position) {
            dataBeen.remove(position);
            notifyDataSetChanged();
        }
        public void initRefresh(List<MerchandiseStoreDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchandiseStoreDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }


    }




    public void query(int pagenow) {
          if(mActivity.swiperefresh!=null){
              mActivity.swiperefresh.setRefreshing(true);
          }
        final Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsId",mActivity.merchantsId+"");
        Xutils.POST(HttpUrl.merchandisebymerchantidfenye, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
             System.out.println("*********************");
                if(mActivity.swiperefresh!=null){
                mActivity.swiperefresh.setRefreshing(false);
            }

                Gson gson = new Gson();
                MerchandiseStoreDomain domain = gson.fromJson(result, MerchandiseStoreDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),mActivity));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (AllProduceFragment.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                AllProduceFragment.this.pagenow++;
                                                append(AllProduceFragment.this.pagenow);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }

                        break;
                    case HttpCode.ERROR:
             //           Toast.makeText(mActivity.getApplicationContext(),""+domain.getMessage(),Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if(mActivity.swiperefresh!=null){
                    mActivity.swiperefresh.setRefreshing(false);
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow) {
        lastloading=true;
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsId",mActivity.merchantsId+"");
        Xutils.POST(HttpUrl.merchandisebymerchantidfenye, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                MerchandiseStoreDomain domain = gson.fromJson(result, MerchandiseStoreDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),mActivity));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (AllProduceFragment.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                AllProduceFragment.this.pagenow++;
                                                append(AllProduceFragment.this.pagenow);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                    case HttpCode.ERROR:
                   //     Toast.makeText(mActivity.getApplicationContext(),""+domain.getMessage(),Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
